package com.mystore.dao.impl;

import com.mystore.dao.BaseDao;
import com.mystore.dao.GoodDao;
import com.mystore.entity.Good;
import com.mystore.util.DBUtil;
import com.mystore.vo.GoodVO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodDaoImpl implements GoodDao {

    private BaseDao baseDao;

    public GoodDaoImpl() {
        this.baseDao = new BaseDaoImpl();
    }

    @Override
    public List<GoodVO> findAllGoodByGid(int gid, int pageSize, int pageNumber, Connection connection) {
        String sql = "select g.id,g.name,g.msg,g.price,cg.kind,g.num from good g,category cg  where g.gid=? and g.gid = cg.id LIMIT "+(pageNumber-1)*pageSize+","+pageSize+"";
        List<Object> list = new ArrayList<>();
        list.add(gid);
        List<GoodVO> goodVOList= null;
        try {
             goodVOList = baseDao.findMoreRefResult(sql,list,GoodVO.class,connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        DBUtil.closeConnection(connection);
        return goodVOList;
    }

    @Override
    public Good finById(int id,Connection connection) {
        String sql = "select * from good where id=?";
        List<Object> list = new ArrayList<>();
        list.add(id);
        Good good = null;
        try {
            good = (Good) baseDao.findSingleResult(sql,list,Good.class,connection);
        }catch (Exception e){
            e.printStackTrace();
        }
        return good;
    }

    @Override
    public List<GoodVO> finAllGood(Connection connection) {
        String sql = "select g.id,g.name,g.msg,g.price,g.gid,g.num from good g";
        List<GoodVO> goodVOList= null;
        try {
            goodVOList = baseDao.findMoreRefResult(sql,null,GoodVO.class,connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodVOList;
    }

    /**
     * 查询总条数
     * @param gid
     * @param connection
     * @return
     */
    @Override
    public  int getTotal(int gid,Connection connection)  {
        String sql = "SELECT g.id  FROM good g where g.gid=?";
        List<Object> list = new ArrayList<>();
        list.add(gid);
        List listSize =null;
        try {
            list= baseDao.findMoreRefResult(sql,list, Good.class,connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
       return list.size();
    }


}
